package com.szh.htmltopdf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szh.htmltopdf.mapper.UserMapper;
import com.szh.htmltopdf.model.UserModel;
import com.szh.htmltopdf.pojo.UserVO;
import com.szh.htmltopdf.service.UserService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserModel> implements UserService {
    @Resource
    UserMapper userMapper;
    @Autowired
    private PlatformTransactionManager txManager;
    
    @Resource
    RedissonClient redissonClient;
    @Override
    public List<UserVO> testLombok() {
        List<UserVO> list =  userMapper.testLombokList();
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void testRedissonLockAndTran() {

        int i;
        UserModel model = new UserModel();
        model.setId(4444L);
        model.setName("测试分布式锁");
        i = userMapper.updateById(model);
      
    }

    @Override
    public String testRedissonLockAndManualTran() {
        // 手动开启事务  start
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = txManager.getTransaction(def);
        // 手动开启事务  end

        RLock lock = redissonClient.getLock("11111");
        lock.lock();
        int i = 0;
        try {
            UserModel model = new UserModel();
            model.setId(4444L);
            model.setName("测试分布式锁");
            i = userMapper.updateById(model);
            // 手动提交事务  start
            txManager.commit(status);
            // 手动提交事务  end
            
        } catch (Exception e) {
            e.printStackTrace();
            // 手动回滚事务  start
            txManager.rollback(status);
            // 手动回滚事务  end
            throw new RuntimeException( "充值失败，请重试");
        } finally {
            lock.unlock();
        }
        return "ok"+i;
    }
}
